package com.hui.java.Synchronized;

/**
 * TODO: Synchronized同步代码块
 *
 * @author chenth
 * @create 2019-09-07 17:10
 **/
public class SecondSynchronized {
    /**
     * 当一个线程访问该object的synchronized同步代码块的时候，
     * 另一个线程仍可以访问该object对象中非synchronized同步代码块
     */
    public void method1() {
        synchronized (this) {
            for (int i = 0; i < 5; i++) {
                System.out.println(Thread.currentThread().getName() + " synchronized loop " + i);
            }
            System.out.println(Thread.currentThread().getName() + " is finished!");
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void method2() {
        for (int j = 0; j < 5; j++) {
            System.out.println("This is another Thread " + Thread.currentThread().getName());
        }
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        SecondSynchronized t1 = new SecondSynchronized();
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                t1.method1();
            }
        }, "A");
        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                t1.method2();
            }
        }, "B");
        thread2.start();
        thread1.start();
    }
}
